<template>
   <el-card v-loading="loading">
       <template #header>
           <span>编辑班级 </span>
           <el-tag type="primary">ID：{{id}}</el-tag>
       </template>
        <!-- ref="form":对当前对象的获取，通过$获取当前对象 -->
       <el-form ref="form" :model="form" :rules="rules" label-width="80px">
           <el-form-item label="班级期号" prop="class_name">
               <el-input v-model="form.class_name"></el-input>
           </el-form-item>
           <el-form-item label="状态">
               <el-radio v-model="form.status" label="1">显示</el-radio>
               <el-radio v-model="form.status" label="0">隐藏</el-radio>
           </el-form-item>
           <el-form-item>
               <el-button type="primary" @click="save()">保存</el-button>
               <el-button @click="back()">返回</el-button>
           </el-form-item>
       </el-form>   
   </el-card>
</template>

<script>
export default {
  props: ["id"],
  data() {
    const isClassSame = async (rule, value, callback) => {
      if (value == this.originalForm.class_name) {
        callback();
        return;
      }
      var { data } = await this.axios({
        method: "get",
        url: `/classes/exists/class_name/${value}`
      });
      if (data) {
        callback(new Error("班级期名已存在"));
      } else {
        callback();
      }
    };
    return {
      loading: false,
      form: {
        class_name: "",
        status: ""
      },
      rules: {
        class_name: [
          { required: true, message: "班级期名必须填写！" },
          {
            validator: (rule, value, callback) => {
              if (/^[0-9]*$/.test(value)) {
                callback();
              } else {
                callback(new Error("班级期号必须是数字"));
              }
            }
          },
          { validator: isClassSame }
        ]
      }
    };
  },
  created() {
    this.getClass();
  },
  methods: {
    async getClass() {
      this.loading = true;
      const { data: { data } } = await this.axios({
        url: `/classes/${this.id}`
      });
      this.originalForm = data;
      this.form.class_name = data.class_name;
      this.form.status=data.status;
      this.loading=false;    
    },
    async save() {
      await this.$refs.form.validate(async flag => {
        if (!flag) {
          return;
        }
        this.loading = true;
        await this.axios({
          method: "put",
          url: `/classes/edit/${this.id}`,
          data: {
            class_name: this.form.class_name,
            status: this.form.status
          }
        });
        this.loading = false;
        this.$message.success("更新成功");
        this.$router.push({
          path: "/home/classes"
        });
      });
    },
    back() {
      this.$router.push({ 
        name:'HomeClasses'
       });
    }
  }
};
</script>



